package ru.tulupov.producerconsumerpattern;

import java.util.List;

public class Storage<T> {
	private List<T> elements;

	/**
	 * Creates the storage with specified maximum size
	 * 
	 * @param capacity
	 *            the maximum size
	 */
	public Storage(int capacity) {
		elements = new FixedSizeArrayList<T>(capacity);
	}

	/**
	 * Adds a new element
	 * 
	 * @param element
	 *            the element
	 * @return if added successful true, false - otherwise
	 */
	public synchronized boolean add(T element) throws InterruptedException {
		boolean result = true;

		while (!elements.add(element)) {

			this.wait();

		}

		this.notify();

		return result;
	}

	public synchronized T removeLastElement() {
		T element = null;
		int size = elements.size();

		if (size != 0) {
			element = elements.remove(size - 1);
			this.notifyAll();
		}

		return element;
	}

	/**
	 * Removes and returns the last object from the storage
	 * 
	 * @return the object
	 */
	public synchronized T get() throws InterruptedException {
		T element = null;

		while ((element = removeLastElement()) == null) {

			this.wait();

		}

		return element;
	}

	/**
	 * Returns the storage size
	 * 
	 * @return the storage size
	 */
	public synchronized int size() {

		return elements.size();

	}

	public synchronized boolean isEmpty() {
		return elements.isEmpty();
	}

}